/*
 * @Author: yanjikun
 * @Date: 2022-04-12 17:52:33
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-04-13 16:20:01
 * @Description: file content
 */

import { error } from '@/utils/log'
import { nextTick, ref, unref } from 'vue'
import { ChartActionType, useChartReturnType } from '../types/chart'

export const useChart = (): useChartReturnType => {
  const chartRef = ref<Nullable<ChartActionType>>(null)
  const getChart = async () => {
    const chart = unref(chartRef)
    if (!chart) {
      error('未获取到chart实例,请在执行DOM操作时确保DOM已呈现!')
    }
    await nextTick()
    return chart as ChartActionType
  }
  const register = (ele: ChartActionType) => {
    chartRef.value = ele
  }
  const methods: ChartActionType = {
    reload: async () => {
      const chart = await getChart()
      chart.reload()
    },
    fetchData: async (params) => {
      const chart = await getChart()
      chart.fetchData(params)
    },
    setOption: async (option, clear) => {
      const chart = await getChart()
      chart.setOption(option, clear)
    }
  }
  return [register, methods]
}
